package algorithm;

import algorithm.strategy.IAgeDiffStrategy;

import java.util.ArrayList;
import java.util.List;

/**
 * 获取策略查找年龄差值
 */
public class AgeDiffFinder {
    private final List<Person> persons;

    public AgeDiffFinder(List<Person> persons) {
        this.persons = persons;
    }

    /**
     * 根据查获策略, 获取年龄差
     */
    public PersonAgeDiff find(IAgeDiffStrategy ageDiffStrategy) {
        List<PersonAgeDiff> ageDiffList = new ArrayList<>();

        int size = persons.size();
        for (int i = 0; i < size - 1; i++) {
            for (int j = i + 1; j < size; j++) {
                PersonAgeDiff ageDiff = createPersonAgeDiff(i, j);
                ageDiffList.add(ageDiff);
            }
        }

        if (ageDiffList.size() < 1) {
            return new PersonAgeDiff();
        }

        return ageDiffStrategy.get(ageDiffList);
    }

    /**
     * 创建 PersonAgeDiff 对象, 并且保证对象里 person2 年龄比 person1 的大
     */
    private PersonAgeDiff createPersonAgeDiff(int i, int j) {
        PersonAgeDiff ageDiff = new PersonAgeDiff();

        if (persons.get(i).compareWith(persons.get(j)) < 0) {
            ageDiff.person1 = persons.get(i);
            ageDiff.person2 = persons.get(j);
        } else {
            ageDiff.person1 = persons.get(j);
            ageDiff.person2 = persons.get(i);
        }
        ageDiff.calcAgeDiff();
        return ageDiff;
    }
}